<template>
	<view class="page page-grey page-product-view">
		<view class="page-content">
			<fui-swiper-dot class="swiper-dot" :items="productData.sliderPicUrls" :styles="{ activeBackground: '#FFFFFF' }"
				:current="currentSwiper">
				<swiper class="fui-banner__wrap" @change="onChangeSwiper" circular :indicator-dots="false" autoplay
					:interval="4000" :duration="150">
					<swiper-item  class="goods-swiper-item" v-for="(item, index) in productData.sliderPicUrls" :key="index">
						<view class="fui-banner__item">
							<image style="background: antiquewhite;" class="page-content-image goods-swiper-image" :src="item" mode="widthFix"></image>
						</view>
					</swiper-item>
				</swiper>
			</fui-swiper-dot>
      <view class="reject-wrapper" v-if="productStatus === '已驳回'">
        <view class="reject-title"><fui-icon name="clear-fill" size="40" color="#e9574f"></fui-icon> 驳回原因：</view>
        <view class="reject-reason">{{ productData.auditMsg }}</view>
      </view>
			<card-component class="card" :showTitle="false" :showImage="false">
				<template #default>
					<view class="card-title">
						<view class="card-title-text">{{ productData.name }}</view>
					</view>
					<view class="card-row card-title-row">
            <view class="card-row-category">
              <text class="card-label">分类：</text>
              <text class="">{{ productData.productCategory }}</text>
            </view>
            <view class="card-row-price">
							<text>￥</text>
							<text
								class="card-title-price-text">{{ utils.moneyFormatter(productStartPrice / 100) }}</text>
							<text>/{{productData.unit}}</text>
						</view>
					</view>
				</template>
			</card-component>
			<card-component class="card" :showTitle="false" :showImage="false">
				<template #default>
					<view class="card-row card-row-first">
						<text class="card-label">起售数量</text>
						<text class="card-value">{{ productData.prices?productData.prices[0].startNum:''}}</text>
						<text class="card-value card-unit">{{productData.unit}}</text>
					</view>
					<view class="card-row" v-if="productData.fhdName">
						<text class="card-label">发货地</text>
						<text class="card-value">{{ productData.fhdName }}</text>
					</view>
					<view class="card-row">
						<view class="">
							<text class="card-label">商品属性</text>
						</view>
						<view class="card-region card-region-top">
							<view class="card-region-box">
								<view class="region-item" v-for="item in productData.basics" :key="item.id">
									<text class="region-label">{{item.name}}：</text>
									<text class="region-value">{{ item.value }}</text>
								</view>
							</view>
						</view>
					</view>
					<view class="card-row">
						<view class="">
							<text class="card-label">价格</text>
						</view>
						<view class="card-region" v-for="item in productData.prices" :key="item.value2">
							<view class="card-region-row">
								<view class="region-item">
									<text class="region-label">起售数量：</text>
									<text class="region-value">{{ item.startNum }}{{productData.unit}}</text>
								</view>
								<view class="region-item">
									<text class="region-label">起售价格：</text>
									<text class="region-value region-color">￥</text>
									<text class="region-value region-color region-price">
										{{ utils.moneyFormatter((productData.status == 1 && item.realPrice) ? item.realPrice / 100 : item.price / 100)  }}</text>
									<text class="region-value region-color">/{{productData.unit}}</text>
								</view>
							</view>
						</view>
					</view>
				</template>
			</card-component>
			<view class="model-title">详情介绍</view>

			<card-component class="card" :showTitle="false" :showImage="false">
				<template #default>
					<text class="description mb20">
						{{productData.description}}
					</text>
					<image v-for="(item, index) in productData.picUrl" :key="index" class="detail-image" style="background: antiquewhite;"
						:src="item" mode="widthFix">
					</image>
				</template>
			</card-component>

			<view class="model-title">售后须知</view>
			<card-component class="card" :showTitle="false" :showImage="false">
				<template #default>
					<text class="description">
						{{productData.afterSaleAlert}}
					</text>
				</template>
			</card-component>

			<view class="model-title">交易须知</view>
			<card-component class="card" :showTitle="false" :showImage="false">
				<template #default>
					<text class="description">
						{{productData.tradeAlert}}
					</text>
				</template>
			</card-component>

			<!-- 供应链直供商品，已下架不显示按钮 -->
			<view class="btn-box">
				<view class="submit-btn" v-if="productStatus === '已上架'">
					<fui-button @click="handleUnder" class="btn" width="100%" height="78rpx" background="#EA5750"
						text="下架"></fui-button>
				</view>
				<view class="submit-btn" v-if="isSelf && productStatus === '审核中'">
					<fui-button @click="handleCancel" class="btn" width="100%" height="78rpx" background="#EA5750"
						text="取消申请"></fui-button>
				</view>
				<view class="submit-btn1" v-if="!isSelf && productStatus === '审核中'">
					<fui-button class="btn" width="25vw" @click="handleSetSellPrice" height="78rpx" color="#333333" plain
						borderColor="#707070" text="设置售价"></fui-button>
					<fui-button class="btn" width="25vw" @click="tab.navigateTo(rejectLink)" height="78rpx" color="#F95A5A" plain
						borderColor="#F95A5A" text="驳回"></fui-button>
					<fui-button class="btn" width="25vw" disabledBackground="#EFEFEF" disabledColor="#6e6e6e"
						@click="handleResolve" height="78rpx" background="#F95A5A" text="通过"></fui-button>
				</view>
				<view class="submit-btn1" v-if="isSelf && productStatus === '已驳回'">
					<fui-button class="btn" width="25vw" @click="handleEdit" height="78rpx" color="#333333" plain
						borderColor="#707070" text="编辑"></fui-button>
					<fui-button class="btn" width="25vw" @click="tab.navigateTo(releaseLink)" height="78rpx" background="#F95A5A"
						text="上架"></fui-button>
				</view>
				<view class="submit-btn1" v-if="isSelf && productStatus === '已下架'">
					<fui-button class="btn" width="25vw" @click="handleRemove" height="78rpx" color="#333333" plain
						borderColor="#707070" text="移除"></fui-button>
					<fui-button class="btn" width="25vw" @click="tab.navigateTo(changePriceLink)" height="78rpx" color="#333333" plain
						borderColor="#707070" text="改价"></fui-button>
					<fui-button class="btn" width="25vw" @click="tab.navigateTo(releaseLink)" height="78rpx" background="#F95A5A"
						text="上架"></fui-button>
				</view>
				<view class="submit-btn1" v-if="isSelf && productStatus === '商品信息'">
					<fui-button class="btn" width="25vw" @click="handleRemove" height="78rpx" color="#333333" plain
						borderColor="#707070" text="移除"></fui-button>
					<fui-button class="btn" width="25vw" @click="handleEdit" height="78rpx"
						background="#F95A5A" text="编辑"></fui-button>
				</view>
			</view>
		</view>
	</view>
</template>

<script setup>
import { ref, computed, inject, watch } from 'vue'
import { onLoad, onShow } from '@dcloudio/uni-app'
import { useStore } from 'vuex'
import { setTitle } from '@/utils/common'
import utils from '@/components/firstui/fui-utils'
import CardComponent from '@/components/card/normal'
import productApi from '@/api/product'

const store = useStore()
const tab = inject('$tab')
const modal = inject('$modal')

const userType = computed(() => store.getters.userType)
const isSelf = ref(false)
const isCatalog = ref(false)

// 轮播图
const currentSwiper = ref(0)
const onChangeSwiper = (e) => {
	currentSwiper.value = e.detail.current
}

// 商品详情：审核状态：auditState  0-审核中 1-通过 2-驳回  商品状态：status 0-下架 1-上架
const productId = ref('')
const productData = ref({})
const productStatus = computed(() => {
	let status = ''
	if (productData.value.status === 1) status = '已上架'
	if (productData.value.status === 2 && productData.value.auditState === 0) status = '审核中'
	if (productData.value.status === 2 && productData.value.auditState === 2) status = '已驳回'
	if (productData.value.status === 0) status = '已下架'
	if (isCatalog.value) status = '商品信息'
	setTitle(status)
	return status
})
const productStartPrice = computed(() => {
	let price = 0
	if (productData.value.prices && productData.value.prices[0]) {
		price = (productData.value.status === 1 && productData.value.prices[0].realPrice) ? productData.value.prices[0].realPrice : productData.value.prices[0].price
	}
	return price
})
const getProductDetail = () => {
	modal.loading()
	try {
		productApi.getProductDetail(productId.value).then((res) => {
			modal.closeLoading()
			if (res.code === 0) {
				const productCategory = store.getters.productCategoryList.filter((item) => item.id === res.data.categoryId)
				const obj = {
					...res.data,
					picUrl: JSON.parse(res.data.picUrl),
					productCategory: productCategory[0]?.name
				}
				if (res.data.prices && res.data.prices[0]) {
					obj.costPrice = res.data.prices[0].costPrice ? res.data.prices[0].costPrice / 100 : 0
				}
				store.commit('SET_DETAIL_ORIGIN_DATA', JSON.parse(JSON.stringify(obj)))
				
				if (tempPriceData.value) {
					obj.prices = [...tempPriceData.value]
				}
				productData.value = obj
				store.commit('SET_DETAIL_DATA', obj)
			} else {
				modal.msgError(res.msg)
			}
		})
	} catch (err) {
		modal.closeLoading()
		modal.msgError(err.msg)
	}
}

onLoad((option) => {
	productId.value = option.productId
	isSelf.value = option.isSelf === 'true'
	isCatalog.value = option.isCatalog === 'true'

	store.commit('SET_DETAIL_AGREE', false)
})

const tempPriceData = ref(null)
onShow(() => {
	getProductDetail()
	uni.$once('onSetPrices', data => {
    tempPriceData.value = data
  })
})

const releaseLink = computed(() => `/pages/goods/newRelease?isDetail=true`) // 商品上架
const rejectLink = computed(() => `/pages/goods/reject?id=${productId.value}`) // 驳回申请
const changePriceLink = computed(() => `/pages/goods/price?isSetPrice=false&unit=${productData.value.unit}`) // 商品改价
const setPriceLink = computed(() => `/pages/goods/price?isSetPrice=true&unit=${productData.value.unit}`) // 设置售价

// 编辑商品
const handleEdit = () => {
	if ((productData.value.auditState == 1 && productData.value.status == 1) || (productData.value.auditState === 0)) {
		modal.msgError('请取消上架之后编辑')
	}
	tab.navigateTo(`/pages/goods/addGoods?id=${productId.value}&productCategory=${productData.value.productCategory}`)
}

// 设置售价
const handleSetSellPrice = () => {
	if (store.getters.detailAgree) {
		modal.confirm('售价已设置，是否要重新设置售价？').then(() => {
			tab.navigateTo(setPriceLink.value)
		})
	} else {
		tab.navigateTo(setPriceLink.value)
	}
}

// 通过申请
const handleResolve = () => {
	if (!store.getters.detailAgree) {
		modal.msgError('请设置售价之后再通过')
		return
	}
	modal.confirm(`您确认要审核通过商品【${productData.value.name}】上架申请 ？`).then(() => {
		try {
			const editPrices = productData.value.prices.map((item) => {
				return { pricesId: item.id, priceAfter: item.price }
			})
			productApi.doAudit({
				id: productId.value,
				auditState: 1,
				editPrices: editPrices
			}).then((res) => {
				if (res.code === 0) {
					modal.msgSuccess('商品已通过审核')
					setTimeout(() => {
						tab.navigateBack()
					}, 1000)
				} else {
					modal.msgError(res.msg)
				}
			})
		} catch (err) {
			console.log(err)
			modal.msgError(err.msg)
		}
	})
}

// 取消申请
const handleCancel = () => {
	modal.confirm(`您确认取消商品【${productData.value.name}】的上架申请？`).then(() => {
		try {
			productApi.cancelRelease(productId.value).then((res) => {
				if (res.code === 0) {
					modal.msgSuccess('取消成功')
					setTimeout(() => {
						tab.navigateBack()
					}, 1000)
				} else {
					modal.msgError(res.msg)
				}
			})
		} catch (err) {
			modal.msgError(err.msg)
		}
	})
}

// 商品下架
const handleUnder = () => {
	modal.confirm(`您确认下架商品【${productData.value.name}】？`).then(() => {
		try {
			productApi.removeProduct({
				id: productId.value,
				status: 0
			}).then((res) => {
				if (res.code === 0) {
					modal.msgSuccess('下架成功')
					setTimeout(() => {
						tab.navigateBack()
					}, 1000)
				} else {
					modal.msgError(res.msg)
				}
			})
		} catch (err) {
			modal.msgError(err.msg)
		}
	})
}

// 移除商品
const handleRemove = () => {
	if (productData.value.status == 1) {
		modal.msgError('当前商品已上架商城，不允许移除！')
		return
	}
	if (productData.value.stock) {
		modal.msgError('当前商品库存大于0，不允许移除！')
		return
	}
	modal.confirm(`您确认移除商品【${productData.value.name}】？`).then(() => {
		try {
			productApi.removeProduct({
				id: productId.value,
				status: -1
			}).then((res) => {
				if (res.code === 0) {
					modal.msgSuccess('移除成功')
					setTimeout(() => {
						tab.navigateBack()
					}, 1000)
				} else {
					modal.msgError(res.msg)
				}
			})
		} catch (err) {
			modal.msgError(err.msg)
		}
	})
}
</script>

<style lang="scss" scoped>
.page {
	width: 100%;
	background-color: #f2f4f5;
	min-height: 100%;

	&-content {
		width: calc(100% - 56rpx);
		margin: 0 auto;
		padding-bottom: 150rpx;

		&-image {
			width: 100vw;
		}
	}

	.reject-wrapper {
		margin-top: 24rpx;
		background-color: rgba(233, 87, 79, .1);
		border-radius: 12rpx;
		padding: 24rpx;
		.reject-title {
			display: flex;
			align-items: center;
			margin-bottom: 20rpx;
			font-size: 28rpx;
			font-weight: bold;
			color: #e9574f;
			.fui-icon {
				margin-right: 5rpx;
			}
		}
		.reject-reason {
			font-size: 28rpx;
			color: #e9574f;
		}
	}

	.card {
		margin-top: 20rpx;

		&-title {
			display: flex;
			justify-content: space-between;
			align-items: center;
			font-size: 32rpx;
			color: #e9574f;
			font-weight: bold;

			&-text {
				color: #333333;
			}

			&-price {
				font-size: 28rpx;

				&-text {
					font-size: 44rpx;
					display: inline-block;
					margin: 0 8rpx 0 2rpx;
				}
			}
		}

		&-row {
			font-size: 28rpx;
			font-weight: 400;
			color: #999999;
			margin-top: 16rpx;

			&.card-title-row {
				display: flex;
				justify-content: space-between;
				align-items: center;

				.card-row-price {
					font-size: 28rpx;
					color: #e9574f;

					.card-title-price-text {
						font-size: 44rpx;
						font-weight: bold;
						display: inline-block;
						margin: 0 8rpx 0 2rpx;
					}
				}
			}

			&-first {
				margin: 0;
			}
		}

		&-label {
			display: inline-block;
		}

		&-value {
			font-weight: 400;
			color: #666666;
			margin-left: 20rpx;
		}

		&-unit {
			margin-left: 8rpx;
		}

		&-region {
			width: 100%;
			background: #f2f8ff;
			border-radius: 12rpx 12rpx 12rpx 12rpx;
			padding: 20rpx 40rpx;
			margin-top: 12rpx;
			box-sizing: border-box;

			&-row {
				display: flex;
				align-items: center;
				flex-wrap: wrap;

				.region-item {
					min-width: 50%;
					font-size: 24rpx;
					font-weight: 400;

					.region-label {
						color: #666666;
					}

					.region-value {
						color: #333333;
					}

					.region-color {
						color: #e9574f;
						font-size: 28rpx;
						font-weight: bold;
					}

					.region-price {
						margin: 0 8rpx 0 6rpx;
					}
				}
			}

			&-lastrow {
				.region-item {
					margin-bottom: 0rpx;
				}
			}
		}
	}

	.description {
		display: block;
		font-size: 24rpx;
		font-weight: 400;
		color: #666666;
		&.mb20 {
			margin-bottom: 20rpx;
		}
	}

	.model-title {
		font-size: 32rpx;
		font-weight: bold;
		color: #333333;
		margin-bottom: 20rpx;
	}

	.detail {
		background-color: #ffffff;
		// margin-left: -28rpx;
		// width: 100vw;

		&-image {
			width: 100%;
			// height: 1760rpx;
		}
	}

	.btn-box {
		position: fixed;
		bottom: 0;
		right: 0;
		width: 100%;
		padding: 20rpx;
		box-sizing: border-box;
		background-color: #ffffff;

		.submit-btn {
			display: flex;
			justify-content: space-between;
			width: 100%;
		}


		.submit-btn1 {
			display: flex;
			justify-content: flex-end;
			width: 100%;

			.btn {
				margin-right: 20rpx !important;
			}
		}
	}

	.submit-btn2 {
		display: flex;
		justify-content: space-between;
		width: 100%;
		margin-top: 36rpx;

		.btn {
			font-weight: 400;
		}
	}

	/* 自定义内容区样式需自行控制 */
	.fui-custom__wrap {
		width: 100%;
		height: 490rpx;
		display: flex;
		flex-direction: column;
		padding: 34rpx 36rpx 76rpx;
		box-sizing: border-box;
		font-weight: bold;

		.content {
			padding: 0 36rpx;
			box-sizing: border-box;

			.row {
				display: flex;
				align-items: center;
				margin: 32rpx 0 20rpx;
			}

			.title {
				font-size: 32rpx;
				color: #333333;
			}

			.label {
				font-size: 28rpx;
				color: #333333;
				margin-right: 36rpx;
			}

			.value {
				font-size: 44rpx;
				color: #e9574f;
				margin: 0 8rpx 0 2rpx;
			}

			.unit {
				font-size: 28rpx;
				color: #e9574f;
			}

			.input {
				margin-top: 14rpx;
				font-weight: 400;
			}
		}
	}

	.fui-banner__item {
		width: 100%;
		height: 434rpx;
		color: #ffffff;
		display: flex;
		align-items: center;
		justify-content: center;
		font-size: 34rpx;
		font-weight: 600;
	}

	.fui-banner__wrap {
		height: 434rpx;
		width: 100%;
		.goods-swiper-item {
			background-color: #fff;
			.goods-swiper-image {
				width: 100%;
				min-height: 100%;
				height: 100%;
			}
		}
	}

	.swiper-dot {
		width: 100vw;
		margin-left: -28rpx;
		height: 434rpx;
	}

	.card-region-box {
		display: flex;
		align-items: center;
		flex-wrap: wrap;

		.region-item {
			width: 50%;
			margin-bottom: 24rpx;
		}
	}

	.card-region-top {
		padding-bottom: 0;
	}
}
</style>